//
//  BN_DynamicParentData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-29.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_DynamicParentData.h"

@implementation BN_DynamicParentData {
    
    NSArray *files_;
    NSInteger replTime_;
}

/**
 *  拿到闫老师从网络获得的数据
 */
- (void)loadNetData {
    
    /**
     *  解决block 循环问题 添加 blockSelf_
     */
    __block BN_DynamicParentData *blockSelf_ = self;
    // 测试加载第一页
    [_dynamicHelper refreshClassList];
    _dynamicHelper.queryParentListCompleteHandler = ^(id result,NSString *errorMsg){
        // update by jason yan 2014-05-30
        if (errorMsg) {
            NSLog(@"%@",errorMsg);
             [[NSNotificationCenter defaultCenter]postNotificationName:KDYNAMIC_HINTMESSAGE object:errorMsg];
        }
        if(result){
            NSLog(@"家长动态列表:%@",result);
            [blockSelf_ useNetDate:result];
        }
    };
    // 测试加载第一页
    [_dynamicHelper refreshParentList];
    
}

// 得到下一页数据
- (void)loadNextNetData {
    __block BN_DynamicParentData *blockSelf_ = self;
    _dynamicHelper.queryParentListCompleteHandler = ^(id result,NSString *errorMsg){
          // update by jason yan 2014-05-30
        if (errorMsg) {
            NSLog(@"%@",errorMsg);
            [[NSNotificationCenter defaultCenter]postNotificationName:KDYNAMIC_HINTMESSAGE object:errorMsg];
        }
        if (result) {
            NSLog(@"第二页班级动态列表:%@",result);
            [blockSelf_ useNetDate:result];
        }
    };
    // 测试加载第二页班级动态
    [_dynamicHelper fetchNextPageForParent];
}

// 获得数据 重新加载Tableview
- (void)useNetDate:(id)info {
    self.netArray = (NSMutableArray *)info;
    self.listReload(YES);
}

/**
 *  计算cell高度
 */
- (float)calcCellHeight:(NSIndexPath *)indexPath {
    NSString *fileFlgStr = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"fileFlg"]];
    float height = 0.0;
    
    // notiSubj 高度
    NSString *notiSubj = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postSubj"]];
    UIFont * contLabelfont = [UIFont systemFontOfSize:APP_CONTENT_FONT_SIZE];
    CGSize contLabelsize = CGSizeMake(296,10000);
    NSDictionary * contLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:contLabelfont,NSFontAttributeName,nil];
    CGSize contLabelActualsize = [self getTextSize:contLabelsize disFont:contLabelfont contentStr:notiSubj contextDic:contLabeldic];
    NSLog(@"%f",contLabelActualsize.height);
    
    
    files_ = self.netArray[indexPath.row][@"files"];
    replTime_ = [self.netArray[indexPath.row][@"replTime"]integerValue];
    
    // 评论View高度
    NSInteger replCount = 0;
    if (replTime_ >= 3) {
        replCount = 3*15+10;
    }
    if (replTime_ == 2) {
        replCount = 2*15+5;
    }
    if (replTime_ == 1) {
        replCount = 15;
    }
    if (replTime_ == 0) {
        replCount = -15;
    }
    
    
    // 判断视频||图片
    // 视频
    if ([fileFlgStr isEqualToString:@"1"]) {
        height = 409+replCount+(contLabelActualsize.height-15);
    }else {
        if (files_.count == 1) {
            
            height = 475+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 2) {
            height = 315+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 3) {
            height = 315-(160-106)+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 4) {
            height = 315+160+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 5 || files_.count == 6) {
            height = 315+(160-106)+replCount+(contLabelActualsize.height-15);
        }
        
        if (files_.count > 6) {
            height = 315+(160-106)+106+replCount+(contLabelActualsize.height-15);
        }
    }
    return height;
}

- (id)init {
    if (self = [super init]) {
        // 初始化动态Helper
        _dynamicHelper = [[BN_DynamicHelper alloc]init];
        [self performSelectorInBackground:@selector(loadNetData) withObject:nil];
        /**
         *  添加触发Tableview Reload通知
         */
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadDataForParentTableView) name:KRELOADCLASSTABLEVIEW object:nil];
        /**
         *  添加触发TableView refresh
         */
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(autoRefreshParentTableView:) name:KPARENTAUTOREFRESH object:nil];
    }
    return self;
}

- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNetData];
    [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

#pragma mark - 刷新控件的代理方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

- (void)reloadParentList {
    self.listReload(YES);
}

float currentContentOffset;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    currentContentOffset = scrollView.contentOffset.y;
    
    // 切换的View隐藏时-慢慢向下拉-拉到最底部时-切换的View显示
    if (currentContentOffset == -99) {
        [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
    }
}

#pragma mark 列表的委托与dataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    float height;
    if (self.netArray.count > 0) {
        height = [self calcCellHeight:indexPath];
    }else {
        height = 360;
    }
    return height;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"BN_DynamicCell";
    BN_DynamicCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BN_DynamicCell" owner:nil options:nil]objectAtIndex:0];
        cell.tag = indexPath.row;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    for (UIView *view in cell.displayImageView.subviews) {
        [view removeFromSuperview];
    }
    for (UIView *view in cell.replView.subviews) {
        [view removeFromSuperview];
    }
    
    [cell toUpdateListData:^(BOOL isUpdate, NSInteger pageNumber) {
        if (isUpdate) {
            [self performSelectorInBackground:@selector(loadNetData) withObject:nil];
        }
    }];
    
    // 用户权限
    NSInteger postUserType = [self.netArray[indexPath.row][@"postUserType"] integerValue];
    [self dynamicUserType:cell.deleteDynamicBtn userType:postUserType];
    
    // 是否收藏
    cell.favoFlg = [self.netArray[indexPath.row][@"favoFlg"] integerValue];
    
    cell.infoArray = self.netArray;
    
    // postId
    cell.postId = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postId"]];
    
    // 滑动最后一个CELL时 加载数据
    cell.userName.text = self.netArray[indexPath.row][@"postUserName"];
    
    NSString *dateStr = self.netArray[indexPath.row][@"postDate"];
    NSRange rang = NSMakeRange(10, 6);
    NSString * strRang = [dateStr substringWithRange:rang];
    cell.sendTime.text = strRang;
    
    // 赞
    cell.praiFlg = [self.netArray[indexPath.row][@"praiFlg"]intValue];
    cell.praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    NSString *praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    cell.likeLabel.backgroundColor = [UIColor clearColor];
    cell.likeLabel.text = praiTime;
    [cell dealLikeBtnColorState];

    // 浏览次数 browTime
    NSString *browTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"browTime"]];
    if (![browTime isEqual:[NSNull null]]) {
        cell.lookTimes.text = [NSString stringWithFormat:@"浏览%@次",browTime];
    }else {
        cell.lookTimes.text = @"浏览0次";
    }
    
    // 评论数量 replTime 居然是数值型....
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];
    NSString *replTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    if (![replTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.pingLunBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *pinlunLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {
            case 7:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                break;
            case 6:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                break;
        }
        pinlunLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        pinlunLabel.textColor = color;
        pinlunLabel.font = [UIFont systemFontOfSize:12];
        pinlunLabel.text = replTime;
        [cell.pingLunBtn addSubview:pinlunLabel];
    }
    
    // fileFlg 为0是图片 1为视频
    NSArray *files = self.netArray[indexPath.row][@"files"];
    NSString *fileFlg = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"fileFlg"]];
    if ([fileFlg isEqualToString:@"0"]) {
        NSLog(@"%ld",(long)indexPath.row);
        NSArray *files = self.netArray[indexPath.row][@"files"];
        [cell imgArray:files];
    }else {
        [cell video:files];
    }
    
    // 文字内容
    NSString *postSubj = self.netArray[indexPath.row][@"postSubj"];
    if (![postSubj isEqual:[NSNull null]]) {
        cell.contentText.text = postSubj;
    }
    
    [cell.contentText sizeToFit];
    [cell relayout];
    // 评论数
    cell.replArr = self.netArray[indexPath.row][@"repls"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
}

// 判断向上或向下滚动
float lastContentOffset;
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    if (currentContentOffset > 0) {  // 解决班级动态UIView和下拉刷新冲突
        NSLog(@"%f",lastContentOffset);
        if (lastContentOffset < scrollView.contentOffset.y) {
            NSLog(@"向上滚动显示");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"hide"];
            
        }else{
            NSLog(@"向下滚动隐藏");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
            
        }
    }
}

#pragma mark 封装自动撑开高度的方法
- (CGSize)getTextSize:(CGSize)provisionsSize disFont:(UIFont *)font contentStr:(NSString *)contentStr contextDic:(NSDictionary *)contextDic {
    
    CGSize size;
    switch (MAIN_VERSION) {
        case 7:
            size =[contentStr boundingRectWithSize:provisionsSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:contextDic context:nil].size;
            
            break;
            
        case 6:
            size = [contentStr sizeWithFont:font constrainedToSize:provisionsSize lineBreakMode:UILineBreakModeWordWrap];
            break;
        default:
            break;
    }
    return size;
}

#pragma mark dealloc
- (void)dealloc
{
    NSLog(@"动态_家长 Modal 释放");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KDISPLAYHIDEDYNAMICUIVIEW object:nil];
    // KDYNAMIC_HINTMESSAGE
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KDYNAMIC_HINTMESSAGE object:nil];
}

#pragma mark
#pragma mark Notification Action 

- (void)autoRefreshParentTableView:(NSNotificationCenter *)notification {
    if (!self.dynamicHelper) {
        self.dynamicHelper = [[BN_DynamicHelper alloc]init];
    }
    [self loadNetData];
}

- (void)reloadDataForParentTableView {
    [self loadNetData];
}

@end
